<template>
    <div class="h-[10%] bg-gray-200 border-b border-gray-300 flex items-center px-3 justify-between" v-if="curConversation">
        <h3 class="font-semibold  text-gray-900">{{curConversation.title}}</h3>
        <span class="text-sm text-gray-500">{{ dayjs(curConversation.updatedAt).format('YYYY-MM-DD HH:mm:ss') }}</span>
    </div>
    <div class=" w-[80%] mx-auto items-center h-[75%] overflow-y-auto pt-2">
         <MessageList :messages="filteredMessages" />
    </div>
    <div class=" w-[80%] mx-auto flex items-center h-[15%]">
        <MessageInput @create="sendNewMessage" v-model="inputValue"/>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useConversationStore } from '../stores/conversation';
import { useMessageStore } from '../stores/message';
import MessageList from '../components/MessageList.vue';
import MessageInput from '../components/MessageInput.vue';
import { MessageProps } from '../types'
import { db } from '../db'
import dayjs from 'dayjs'

const inputValue = ref('')
const route = useRoute()
const conversationStore = useConversationStore()
const messageStore = useMessageStore()
const conversationId = ref(parseInt(route.params.id as string))
const initMessageId = parseInt(route.query.init as string)
const curConversation = computed(() => conversationStore.getConversationById(conversationId.value))
const filteredMessages = computed(() => messageStore.items)

// const lastQuestion = computed(() => messageStore.getLastQuestion(conversationId.value))

const sendedMessage = computed(() => 
    filteredMessages.value
        .filter(message => message.status !== 'loading')
        .map(message => {
            return {
                role: message.type === 'question' ? 'user' : 'assistant',
                content: message.content
            }
        })
)
const sendNewMessage = async (question: string) => {
    if (question) {
        const date = new Date().toISOString()
        await messageStore.createMessage({
            content: question,
            conversationId: conversationId.value,
            createdAt: date,
            updatedAt: date,
            type: 'question'
        })
        creatingInitialMessage()
        inputValue.value = ''
    }
}

const creatingInitialMessage = async () => {
    // 添加模拟loading回答
    const createdData: Omit<MessageProps, 'id'> = {
        content: '',
        conversationId: conversationId.value,
        type: 'answer',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        status: 'loading'
    }
    // loading的message同步到数据库、响应式对象
    const newMessageId = await messageStore.createMessage(createdData)

    if (curConversation.value) {
        const curProvider = await db.providers.where({ id: curConversation.value.providerId }).first()
        // 向主进程发送数据
        await window.electronAPI.startChat({
            messageId: newMessageId,    //先传loading状态id，返回实际数据时替换
            providerName: curProvider ? curProvider.name : '',
            selectedModel: curConversation.value.selectedModel,
            messages: sendedMessage.value
        })
    }
}

watch(() => route.params.id, async (newId: string) => {
    conversationId.value = parseInt(newId)
    await messageStore.fetchMessagesByConversationId(conversationId.value)
})
onMounted(async () => {
    await messageStore.fetchMessagesByConversationId(conversationId.value)
    if (initMessageId) {
        creatingInitialMessage()
    }
    window.electronAPI.onUpdateMessage(async (streamData) => {
        // console.log('streamData', streamData)
        messageStore.updateMessage(streamData)
    })
})
</script>